#import "RNSourceListHeader.h"
#import "RNSourceListPlaceholder.h"
#import "RNConstants.h"

@implementation RNSourceListHeader

@synthesize title = title_;
@synthesize childController = childController_;
@synthesize nullPlaceholder = nullPlaceholder_;

-(id)initWithTitle:(NSString *)theTitle withArrayController:(NSArrayController *)controller {
    if (!(self = [super init]))
        return nil;
    
    [self setTitle:theTitle];
    [controller addObserver:self forKeyPath:@"arrangedObjects" options:NSKeyValueObservingOptionNew context:NULL];
    [self setChildController:controller];
    [self setNullPlaceholderWithString:@""];
    
    return self;
}

-(void)setNullPlaceholderWithString:(NSString *)placeholderString {
    RNSourceListPlaceholder *placeholder = [[RNSourceListPlaceholder alloc] init];
    [placeholder setTitle:placeholderString];
    [self setNullPlaceholder:placeholder];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [self willChangeValueForKey:@"children"];
    [self didChangeValueForKey:@"children"];
}

-(NSArray *)children {
    if ([[[self childController] arrangedObjects] count] == 0)
        return [NSArray arrayWithObject:[self nullPlaceholder]];
    return [[self childController] arrangedObjects];
}

-(NSDictionary *)objectDictionary {
    return [NSDictionary dictionaryWithObject:[self title] forKey:RNTitleKey];
}

@end
